package com.app.micaihu.custom.components.downandupload;

import android.text.TextUtils;

import androidx.collection.SimpleArrayMap;

import com.android.volley.VolleyError;
import com.app.micaihu.R;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.game.IDownload;
import com.app.micaihu.configure.AppConfigTools;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.UserInforManager;
import com.app.micaihu.utils.DialogUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.view.utils.DownloadAgainUtils;
import com.app.okhttplib.HttpInfo;
import com.app.okhttplib.OkHttpUtil;
import com.app.okhttplib.annotation.DownloadStatus;
import com.app.okhttplib.bean.DownloadFileInfo;
import com.app.okhttplib.callback.OnDownloadingCallback;
import com.app.okhttplib.callback.ProgressCallback;
import com.app.okhttplib.util.AppUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.StringUtils;
import com.blankj.utilcode.util.Utils;
import com.google.gson.reflect.TypeToken;
import com.jeremyliao.liveeventbus.LiveEventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Guo on 2017/6/7.
 * 下载的帮助类
 */

public class DownloadUtils {


    public static final String CLICKTYPE_DOWNLOAD = "1";//点击下载(第一次)统计
    public static final String CLICKTYPE_DOWNLOADCOMPLETED = "2";//下载完成统计
    public static final String CLICKTYPE_STARTUP = "3";//启动游戏统计


    public static int DOWN_LOAD_COUNT;//游戏小红点 计数


    //    public static final String DOWNLOAD_FILEDIR = Environment.getExternalStorageDirectory().getPath()+"/micaihujunshi/";
    public static final String DOWNLOAD_FILEDIR = AppConfigTools.APKFLODER + File.separator;

    public static final String FILE_START_NAME = "micaihu_";//下载文件的开头名


    //正在下载的 set,包含多个下载的downloadFileInfo(未下载完成的),下载完成后移除掉(key = tag(唯一下载链接,不包含随机数))
    private SimpleArrayMap<String, DownloadFileInfo> downloadingSet = new SimpleArrayMap<>();
//    private HashMap<String, DownloadFileInfo> downloadingSet = new HashMap<>();

    //已经下载完成的set,包含了下载的文件包的回调,当安装完成的时候,进行View 的更新__(key = packageName)
    private SimpleArrayMap<String, ArrayList<OnDownloadingCallback>> installSet = new SimpleArrayMap<>();
//    private  HashMap<String,ArrayList<OnDownloadingCallback>> installSet = new HashMap<>();


    private static volatile DownloadUtils singleton;

    public static DownloadUtils getSingleton() {
        if (null == singleton) {
            synchronized (DownloadUtils.class) {
                if (null == singleton) {
                    singleton = new DownloadUtils();
                }
            }
        }

        return singleton;
    }


    private DownloadUtils() {

    }


    public void down(String url, String fileName) {
        down(url, fileName, null, null);
    }

    public void down(String url, String fileName, IDownload iDownload) {
        down(url, fileName, iDownload, null);
    }

    public void down(String url, String fileName, IDownload iDownload, HashMap<String, Object> key) {
        final String tag = OkHttpUtil.getTag(url);
        if (downloadingSet.containsKey(tag) && downloadingSet.get(tag) != null) {//有过下载
            //如果有过下载,直接拿downloadFileInfo
            DownloadFileInfo downloadFileInfo = downloadingSet.get(tag);
            if (TextUtils.equals(downloadFileInfo.getDownloadStatus(), DownloadStatus.PAUSE)) {
                HttpInfo info = HttpInfo.Builder().addDownloadFile(downloadFileInfo).build();
                OkHttpUtil.Builder().setReadTimeout(15).build(tag).doDownloadFileAsync(info);
            } else if (TextUtils.equals(downloadFileInfo.getDownloadStatus(), DownloadStatus.DOWNLOADING)) {
                downloadFileInfo.setDownloadStatus(DownloadStatus.PAUSE);
            } else if (TextUtils.equals(downloadFileInfo.getDownloadStatus(), DownloadStatus.INIT)) {
                HttpInfo info = HttpInfo.Builder().addDownloadFile(downloadFileInfo).build();
                OkHttpUtil.Builder().setReadTimeout(15).build(tag).doDownloadFileAsync(info);
            } else if (TextUtils.equals(downloadFileInfo.getDownloadStatus(), DownloadStatus.CANCLE)) {
                HttpInfo info = HttpInfo.Builder().addDownloadFile(downloadFileInfo).build();
                OkHttpUtil.Builder().setReadTimeout(15).build(tag).doDownloadFileAsync(info);
            }

        } else {//初次下载
            final DownloadFileInfo fileInfo = new DownloadFileInfo(url, fileName, new ProgressCallback() {
                @Override
                public void onProgressAsync(float percent, long bytesWritten, long contentLength, boolean done) {
                    super.onProgressAsync(percent, bytesWritten, contentLength, done);
                    LogUtils.e("showNotification", " download percent->" + percent);

                    DownloadAgainUtils.showNotification(Utils.getApp().getApplicationContext(), iDownload, (int) percent);
                    HashMap<String, String> hashMap = new HashMap<>();
                    hashMap.put(Config.Extra.progress, String.valueOf(percent));
                    hashMap.put(Config.Extra.url, url);
                    LiveEventBus.get(Config.EventBus.gameDownLoad, HashMap.class).post(hashMap);
                }

                @Override
                public void onResponseMain(String filePath, HttpInfo info) {
                    super.onResponseMain(filePath, info);
                    if (info.isSuccessful()) {
                        if (key != null) {
                            MobclickAgentUtils.event(UmEventId.game_downloadsuccess, key);
                        }
                        NewsDBUtil.getInstance().addGameState(iDownload.getIGameId());
                        DownloadAgainUtils.getManager().cancel(Long.valueOf(iDownload.getIGameId()).intValue());
                        DownloadUtils.getSingleton().removeDownloadFileInfo(tag);
                        removeInstallCallBack(tag);
                        AppUtils.installAPP(AppApplication.getInstance(), new File(info.getRetDetail()));
                    }
                }
            });
            HttpInfo info = HttpInfo.Builder().addDownloadFile(fileInfo).build();
            putDownloadFileInfo(tag, fileInfo);
            OkHttpUtil.Builder().setReadTimeout(120).build(this).doDownloadFileAsync(info);
            LogUtils.e("putDownloadFileInfo", "downloadUtils->" + tag);
        }

    }


    public DownloadFileInfo getDownloadFileInfo(String iTag) {
        if (downloadingSet.containsKey(iTag) && downloadingSet.get(iTag) != null) {
            return downloadingSet.get(iTag);
        }
        return null;

    }


    /**
     * 将下载的Bean 放入到集合中
     *
     * @param tag
     * @param downloadFileInfo
     */
    public void putDownloadFileInfo(String tag, DownloadFileInfo downloadFileInfo) {
        if (!downloadingSet.containsKey(tag)) {
            downloadingSet.put(tag, downloadFileInfo);

        }
    }


    /**
     * 将下载的Bean 从集合移除
     *
     * @param tag
     * @param tag
     */
    public void removeDownloadFileInfo(String tag) {
        if (downloadingSet.containsKey(tag) && downloadingSet.get(tag) != null) {
            downloadingSet.remove(tag);
        }
    }


    /**
     * 将下载完成的 加入到安装回调的集合中
     *
     * @param pkgTag
     * @param onDownloadingCallback
     */
    public void putInstallCallBack(String pkgTag, OnDownloadingCallback onDownloadingCallback) {
        if (installSet.containsKey(pkgTag)) {
            ArrayList<OnDownloadingCallback> onDownloadingCallbacks = installSet.get(pkgTag);
            if (onDownloadingCallbacks == null) {
                onDownloadingCallbacks = new ArrayList<>();
            }

            if (!onDownloadingCallbacks.contains(onDownloadingCallback)) {
                onDownloadingCallbacks.add(onDownloadingCallback);
            }
        } else {
            ArrayList<OnDownloadingCallback> onDownloadingCallbacks = new ArrayList<>();
            onDownloadingCallbacks.add(onDownloadingCallback);

            installSet.put(pkgTag, onDownloadingCallbacks);
        }


    }

    /**
     * 移除掉 安装的回调
     *
     * @param pkgTag
     */
    public void removeInstallCallBack(String pkgTag) {
        if (installSet.containsKey(pkgTag) && installSet.get(pkgTag) != null) {
            installSet.remove(pkgTag);
        }

    }


    /**
     * 安装完成后的回调
     *
     * @param pkgTag
     */
    public void installCallBack(String pkgTag) {
        if (installSet.containsKey(pkgTag)) {

            //如果 当前的安装的listener 中包括这个包名,则进行统计
            MobclickAgentUtils.event(Config.EventBauduId.game_065, "安装游戏成功");
            StatService.onEvent(AppApplication.getInstance(), "065", "安装游戏成功", 1);
            ArrayList<OnDownloadingCallback> onDownloadingCallbacks = installSet.get(pkgTag);
            for (OnDownloadingCallback onDownloadingCallback : onDownloadingCallbacks) {
                onDownloadingCallback.onInstalled(pkgTag);
            }
            removeInstallCallBack(pkgTag);
        }

    }


    /**
     * 提供给我外部的取消弹窗
     *
     * @param iDownload
     * @param onDialogBtnClickListener
     */
    IDownload iDownload;

    public void showCancleDialog(IDownload iDownload, DialogUtils.OnDialogBtnClickListener onDialogBtnClickListener) {
        this.iDownload = iDownload;
        try {
            HashMap<String, String> style = new HashMap<>();
            style.put("title", AppApplication.getInstance().getString(R.string.common_prompt));
            style.put("desc", "确定要删除该游戏吗");
            style.put("btnPosi", AppApplication.getInstance().getString(R.string.common_confirm));
            style.put("btnNega", AppApplication.getInstance().getString(R.string.common_cancel));

            DialogUtils.getInstance().setOnDialogBtnClick(onDialogBtnClickListener);
            DialogUtils.getInstance().showCustomDialog(ActivityUtils.getTopActivity(), style);
        } catch (Exception e) {
        }
    }

    /**
     * 取消 下载
     */
    public void cancleRequest() {
        if (this.iDownload == null) return;
        //移除 下载记录
        if (downloadingSet != null && downloadingSet.get(iDownload.getITag()) != null) {

            //暂时不移除,因为有可能会重新 下载
//            DownloadFileInfo remove = downloadingSet.remove(iDownload.getITag());
            final DownloadFileInfo remove = downloadingSet.get(iDownload.getITag());
            remove.setDownloadStatus(DownloadStatus.CANCLE);

            //后续的操作放到回调中来做

//            Message msg = new CancelRequestMessage(OkMainHandler.CANCEL_DOWNLOAD_CALLBACK,
//                    iDownload.getITag(),
//                    remove).build();
//           OkMainHandler.getInstance().sendMessageDelayed(msg,800);
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    OkHttpUtil.getDefault().cancelRequest(iDownload.getITag());
//                    //将SP中的 当前文件总大小移除
//                    if (remove != null && !TextUtils.isEmpty(remove.getSaveFileNameEncrypt())) {
//                        String saveFileNameEncrypt = remove.getSaveFileNameEncrypt();
//                        AppUtils.remove(saveFileNameEncrypt);
//                        //回调View
//                        List<OnDownloadingCallback> viewCallbackList = remove.getViewCallbackList();
//                        for (OnDownloadingCallback onDownloadingCallback : viewCallbackList) {
//                            onDownloadingCallback.onInit(iDownload.getITag());
//                        }
//                        DownUpLoadHelper.removeTask(saveFileNameEncrypt);
//                        remove.setSaveFileNameEncrypt("");
//                        remove.setDownloadStatus(DownloadStatus.INIT);
//                    }
//                }
//            },1000);
        }

        //删除未完成的文件 和已完成下载的apk文件
//        try {
//            String s = EncryptUtil.MD5StringTo32Bit(iDownload.getITag(), true);
//            File file = new File(DOWNLOAD_FILEDIR + s);
//            if (file.exists() && file.isFile()) {
//                boolean delete = file.delete();
//                LogUtils.e("gzq", "delete = " + file.toString() + "  " + delete);
//
//            }
//            File gameFile = new File(DOWNLOAD_FILEDIR + iDownload.getIPath() + ".apk");
//            if (gameFile.exists() && gameFile.isFile()) {
//                boolean delete = gameFile.delete();
//                LogUtils.e("gzq", "delete = " + gameFile.toString() + "  " + delete);
//
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }


    /**
     * 请求统计的接口
     *
     * @param gameId
     * @param clickType
     */
    public void requestStatisticsInterface(String gameId, final String clickType) {
        if (TextUtils.isEmpty(gameId)) return;
        ParamMap paramMap = new ParamMap();
        paramMap.putEncode("articleId", gameId);
        paramMap.putEncode("type", clickType);
        if (UserInforManager.getInstance().isLogin()) {
            paramMap.putEncode("uid", UserInforManager.getInstance().getUserInfor().getUid());

        } else {
            paramMap.putEncode("uid", "");

        }
        HttpUtils.ParmsMapMD5(paramMap);


        HttpListener<DataBean> listener = new HttpListener<DataBean>() {
            @Override
            public void onStart() {
                super.onStart();
                String type = "";
                if (clickType.equals(CLICKTYPE_DOWNLOAD)) {
                    type = "初次下载";
                } else if (clickType.equals(CLICKTYPE_DOWNLOADCOMPLETED)) {
                    type = "下载完成";
                } else {
                    type = "启动";
                }
                LogUtils.e("gzq", "开始请求   " + type);

            }

            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(DataBean response) {
                String type = "";
                if (clickType.equals(CLICKTYPE_DOWNLOAD)) {
                    type = "初次下载";
                } else if (clickType.equals(CLICKTYPE_DOWNLOADCOMPLETED)) {
                    type = "下载完成";
                } else {
                    type = "启动";
                }
                LogUtils.e("gzq", "请求成功   " + type);

            }
        };
        HttpUtils.addPostRequest(URIContant.GAME_STATISTICS, new TypeToken<DataBean>() {
        }.getType(), "", paramMap, listener);


    }


}
